package org.shunfeng.controller;

import org.shunfeng.pojo.SysUser;
import org.shunfeng.service.UserService;
import org.shunfeng.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

public class UserLoginController extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       req.setCharacterEncoding("UTF-8");
       resp.setCharacterEncoding("UTF-8");
       resp.setContentType("text/html;charset=UTF-8");

       String username = req.getParameter("username");
       String password = req.getParameter("password");

        try {
            SysUser sysUser = userService.login(username, password);
            if (sysUser == null){
                req.getRequestDispatcher("/login.html").forward(req, resp);
            }else {
                req.getSession().setAttribute("user", sysUser);
                req.getRequestDispatcher("/index.jsp").forward(req, resp);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }
}
